document.addEventListener('DOMContentLoaded', function() {

    // 1. 数据卡片数值增长动画
    function animateValue(obj, start, end, duration) {
        let startTimestamp = null;
        const step = (timestamp) => {
            if (!startTimestamp) startTimestamp = timestamp;
            const progress = Math.min((timestamp - startTimestamp) / duration, 1);
            obj.innerHTML = (progress * (end - start) + start).toFixed(obj.dataset.target.includes('.') ? 1 : 0); // Preserve decimal for floats
            if (progress < 1) {
                window.requestAnimationFrame(step);
            }
        };
        window.requestAnimationFrame(step);
    }

    document.querySelectorAll('.dashboard-section .current-value').forEach(span => {
        const target = parseFloat(span.dataset.target);
        animateValue(span, 0, target, 1000); // 1秒动画
    });

    // 进度条动画
    document.querySelectorAll('.dashboard-section .progress-bar').forEach(bar => {
        const progress = parseInt(bar.dataset.progress);
        setTimeout(() => {
            bar.style.width = `${progress}%`;
        }, 100); // 延迟执行，确保动画效果
    });

    // 2. 体重趋势图表 (Chart.js)
    const weightTrendCtx = document.getElementById('weightTrendChart').getContext('2d');
    let weightTrendChart;

    function createOrUpdateWeightChart(labels, data) {
        if (weightTrendChart) {
            weightTrendChart.destroy(); // 销毁旧图表实例
        }
        weightTrendChart = new Chart(weightTrendCtx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [{
                    label: '体重 (kg)',
                    data: data,
                    borderColor: '#10B981',
                    backgroundColor: 'rgba(16, 185, 129, 0.2)',
                    fill: true,
                    tension: 0.3,
                    pointBackgroundColor: '#10B981',
                    pointBorderColor: '#fff',
                    pointHoverBackgroundColor: '#fff',
                    pointHoverBorderColor: '#10B981'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: false,
                        title: {
                            display: true,
                            text: '体重 (kg)'
                        }
                    },
                    x: {
                        title: {
                            display: true,
                            text: '日期'
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        mode: 'index',
                        intersect: false
                    }
                }
            }
        });
    }

    // 模拟数据获取
    function getWeightData(range) {
        switch (range) {
            case 'week':
                return {
                    labels: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
                    data: [68.5, 68.2, 68.0, 68.3, 67.9, 67.7, 67.5]
                };
            case 'month':
                return {
                    labels: Array.from({ length: 30 }, (_, i) => `第${i + 1}天`),
                    data: Array.from({ length: 30 }, (_, i) => 70 - i * 0.15 + Math.random() * 0.5 - 0.25)
                };
            case 'year':
                return {
                    labels: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
                    data: Array.from({ length: 12 }, (_, i) => 75 - i * 0.5 + Math.random() * 1 - 0.5)
                };
            default:
                return { labels: [], data: [] };
        }
    }

    // 初始加载周数据
    const initialData = getWeightData('week');
    createOrUpdateWeightChart(initialData.labels, initialData.data);

    // 时间维度切换事件
    document.querySelectorAll('.trend-analysis-section .btn-outline-secondary').forEach(button => {
        button.addEventListener('click', function() {
            document.querySelectorAll('.trend-analysis-section .btn-outline-secondary').forEach(btn => btn.classList.remove('active'));
            this.classList.add('active');
            const range = this.dataset.timeRange;
            const data = getWeightData(range);
            createOrUpdateWeightChart(data.labels, data.data);
        });
    });

    // 3. 导航交互 (移动端菜单，如果Bootstrap已处理，则不需要额外JS)
    // Bootstrap 5 的导航栏已经包含了响应式和菜单展开/收起功能，无需额外JS。

    // 4. 页面内锚点跳转 (如果需要)
    // 如果需要实现点击导航栏链接平滑滚动到页面某个区块，可以添加以下代码：
    // document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    //     anchor.addEventListener('click', function (e) {
    //         e.preventDefault();
    //         document.querySelector(this.getAttribute('href')).scrollIntoView({
    //             behavior: 'smooth'
    //         });
    //     });
    // });

}); 